﻿using Autofac;
using DevExpress.LookAndFeel;
using DevExpress.Skins;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using DevExpress.XtraTabbedMdi;
using EyFramework.Common;
using EyFramework.Library;
using EyFramework.Sys.Core;
using EyFramework.Sys.Core.Service;
using EyFramework.Sys.Entity;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using EyFramework.Common.Entity;
using Constants = EyFramework.Common.Constants;
using EyFramework.Common.Utils;
using System.IO;

namespace EyFramework.Main
{
    public partial class FrmMain : FrmMainBase, IMdiForm
    {
        private DevExpress.XtraTabbedMdi.XtraTabbedMdiManager xtraTabbedMdiMgr;
        private IniFileUtil iniFile = new IniFileUtil(Path.Combine(DirectoryUtil.GetCurrentDirectory(), "AutoUpdate.ini"));

        /// <summary>
        /// 是否不提示直接退出系统
        /// </summary>
        private bool _isQuit = false;

        public FrmMain()
        {
            InitializeComponent();
            InitMenu();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InitForm();
            AddEvents();
            InitSkin();
        }

        private void InitForm()
        {
            BackgroundImage = Image.FromFile(Globals.appConfigure.AppPath + "\\BackPct.jpg");
            BackgroundImageLayout = ImageLayout.Stretch;
            Text = Globals.GetSysConfig(Constants.CFG_AppName);
            bsiCompany.Caption = Globals.GetSysConfig(Constants.CFG_CompanyName);
            bsiUser.Caption = "【" + Globals.CurrentUser.StaffName + "】";
            bsiCurentUser.Caption = string.Format("操作员：{0}", Globals.CurrentUser.StaffName);
            bsiSys.Caption = string.Format("当前应用：{0}", Globals.CurrentUser.SysName);
            bsiVersion.Caption = string.Format("系统版本：V{0}", iniFile.IniReadValue("AutoUpdate", "AppVersion"));
            bsiIp.Caption = string.Format("本机IP：{0}", GetSystemInfo.GetClientLocalIPv4Address());
            tmMsg.Start();
        }

        /// <summary>
        ///     初始化
        /// </summary>
        /// <param name="splash"></param>
        public void InitUserInterface(IMsg splash)
        {
            try
            {
                SuspendLayout();
                splash.UpdateMessage("正在初始化用户界面...");
                InitDevexpress();
                Application.DoEvents();
                splash.UpdateMessage("正在初始化模块容器...");
                Thread.Sleep(50);
                splash.UpdateMessage("正在初始化系统缓存...");
                Sys.Core.SysCache.InitCache();
                splash.UpdateMessage("正在加载模块...");
                Thread.Sleep(50);
                splash.UpdateMessage("正在初始化用户权限...");
                Thread.Sleep(50);
                splash.UpdateMessage("正在加载系统菜单...");
                Thread.Sleep(50);
                splash.UpdateMessage("正在下载基础数据...");
                Thread.Sleep(50);
                splash.UpdateMessage("加载完毕");
                ResumeLayout();
            }
            catch (Exception ex)
            {
                Globals.ShowException(ex);
            }
        }

        /// <summary>
        /// 初始化Devexpress的控件，让后续操作加快
        /// </summary>
        /// <returns></returns>
        private void InitDevexpress()
        {
            GridControl gridControl = new GridControl();
            gridControl.Dispose();
            GridView gridView = new GridView();
            gridView.Dispose();
            SearchLookUpEdit searchLookUpEdit = new SearchLookUpEdit();
            searchLookUpEdit.Dispose();
            XtraReport report = new XtraReport();
            report.Dispose();
        }

        #region 皮肤

        private void InitSkin()
        {
            foreach (SkinContainer cnt in SkinManager.Default.Skins)
            {
                var item = new BarCheckItem(barMain, false);
                item.Caption = cnt.SkinName;
                barSkin.AddItem(item);
                item.ItemClick += OnSkinClick;
                if (cnt.SkinName == DefaultLookAndFeel.LookAndFeel.SkinName)
                {
                    item.Checked = true;
                    barSkin.Caption = string.Format("皮肤:{0}", item.Caption);
                    barSkin.Hint = barSkin.Caption;
                }
            }
        }

        private void OnSkinClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                loading.ShowWaitForm();
                SetSkinItemUnChecked();
                var skinName = e.Item.Caption;
                DefaultLookAndFeel.LookAndFeel.SkinName = skinName;
                barSkin.Caption = string.Format("皮肤:{0}", e.Item.Caption);
                barSkin.Hint = barSkin.Caption;
                Globals.SetSysConfig(Constants.CFG_SkinName, skinName);
                ((BarCheckItem)e.Item).Checked = true;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
            finally
            {
                loading.CloseWaitForm();
            }
        }

        private void SetSkinItemUnChecked()
        {
            foreach (BarItemLink itemLink in barSkin.ItemLinks) ((BarCheckItem)itemLink.Item).Checked = false;
        }

        #endregion 皮肤

        #region 菜单事件

        private void AddEvents()
        {
            barMain.ItemClick += barMain_ItemClick;
        }

        private void barMain_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.Item.Tag == null || string.IsNullOrEmpty(((SysMenu)e.Item.Tag).PATH)) return;
            SysMenu menu = (SysMenu)e.Item.Tag;
            if (!ShowOpenedPage((SysMenu)e.Item.Tag)) CreateMdiControl((SysMenu)e.Item.Tag);
        }

        #endregion 菜单事件

        /// <summary>
        /// 判断是否已经打开菜单窗体
        /// </summary>
        /// <param name="sysMenu"></param>
        /// <returns></returns>
        public bool ShowOpenedPage(SysMenu sysMenu)
        {
            if (xtraTabbedMdiMgr == null)
            {
                return false;
            }
            if (!string.IsNullOrEmpty(sysMenu.MENU_ID))
            {
                foreach (XtraMdiTabPage page in xtraTabbedMdiMgr.Pages)
                {
                    if (((SysMenu)page.MdiChild.Tag).MENU_ID == sysMenu.MENU_ID)
                    {
                        xtraTabbedMdiMgr.SelectedPage = page;
                        return true;
                    }
                }
            }
            else
            {
                foreach (XtraMdiTabPage page in xtraTabbedMdiMgr.Pages)
                {
                    if (((SysMenu)page.MdiChild.Tag).PATH == sysMenu.PATH &&
                        ((SysMenu)page.MdiChild.Tag).MENU_NAME == sysMenu.MENU_NAME)
                    {
                        xtraTabbedMdiMgr.SelectedPage = page;
                        return true;
                    }
                }
            }

            return false;
        }

        #region 初始化菜单

        private void InitMenu()
        {
            var hasCount = this.toolbarFormControl1.TitleItemLinks.Count;
            var sysMenuService = Globals.container.Resolve<ISysMenuService>();
            var menus = sysMenuService.GetUserMenusBySys(Globals.CurrentUser.UserId, Globals.CurrentUser.SysId);
            var menuCount = 0;
            //1、组织第一级的菜单
            foreach (var sysMenu in menus.Where(p => p.PARENT_ID == "0"))
            {
                var bar = new BarSubItem() { Caption = Globals.MenuShortcut(sysMenu.MENU_NAME, menuCount++), Tag = sysMenu, Id = int.Parse(sysMenu.MENU_ID) };
                toolbarFormControl1.TitleItemLinks.Insert(this.toolbarFormControl1.TitleItemLinks.Count - hasCount, bar);
                toolbarFormManager1.Items.Add(bar);
                foreach (var subMenu in menus.Where(p => p.PARENT_ID == sysMenu.MENU_ID))
                {
                    var subbar = new BarButtonItem(barMain, subMenu.MENU_NAME);
                    subbar.Tag = subMenu;
                    subbar.Id = int.Parse(subMenu.MENU_ID);
                    bar.LinksPersistInfo.Add(new LinkPersistInfo(subbar, false));
                    barMain.Items.Add(subbar);
                }
            }
        }

        #endregion 初始化菜单

        #region 创建MDI窗口(普通窗口)

        public void CreateMdiControl(SysMenu menu)
        {
            if (!IsMdiContainer)
            {
                this.IsMdiContainer = true;
                ShowXtraTabbedMdiMgr();
            }
            ShowLoading();
            object[] args = null;
            if (args == null && !string.IsNullOrEmpty(menu.REMARK))
            {
                args = new object[] { menu.REMARK };
            }
            var ass = Assembly.LoadFrom(Globals.appConfigure.AppPath + "\\" + menu.PATH + ".dll");
            var typeOfLoad = ass.GetType(menu.PATH + "." + menu.COMPONENT, true, true);
            var frmBase = typeOfLoad.InvokeMember(
                null,
                BindingFlags.DeclaredOnly |
                BindingFlags.Public |
                BindingFlags.NonPublic |
                BindingFlags.Instance |
                BindingFlags.CreateInstance,
                null,
                null,
                args) as Form;
            xtraTabbedMdiMgr.MdiParent = this;
            if (frmBase != null)
            {
                frmBase.Dock = DockStyle.Fill;
                frmBase.Text = menu.MENU_NAME;
                frmBase.Tag = menu;
                frmBase.MdiParent = this;
                frmBase.WindowState = FormWindowState.Maximized;
                frmBase.Show();
            }
            CloseLoading();
        }

        #endregion 创建MDI窗口(普通窗口)

        private void bbiLock_ItemClick(object sender, ItemClickEventArgs e)
        {
            FrmLock lockDev = new FrmLock();
            this.Hide();
            if (lockDev.ShowDialog() == DialogResult.OK)
            {
                Show();
                Activate();
            }
            else
            {
                _isQuit = true;
                Close();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!_isQuit)
            {
                if (Globals.ConfirmYesNo("确定退出系统？") != DialogResult.Yes) e.Cancel = true;
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void tmMsg_Tick(object sender, EventArgs e)
        {
            bbiMessage.Appearance.ForeColor =
                bbiMessage.Appearance.ForeColor != Color.Red ? Color.Red : bbiRefreshCache.Appearance.ForeColor;
        }

        private void bbiCaculate_ItemClick(object sender, ItemClickEventArgs e)
        {
            Globals.StartCaculate();
        }

        private void bbiNoteBook_ItemClick(object sender, ItemClickEventArgs e)
        {
            Globals.StartNoteBook();
        }

        private void bbiGeneratorCode_ItemClick(object sender, ItemClickEventArgs e)
        {
            var menu = new SysMenu
            {
                MENU_NAME = "代码自动生成",
                MENU_ID = "-1",
                PATH = "EyFramework.AutoCode",
                COMPONENT = "FrmAutoCode"
            };
            CreateMdiControl(menu);
        }

        private void xtraTabbedMdiMgr_PageRemoved(object sender, MdiTabPageEventArgs e)
        {
            if (e.Page.MdiChild != null)
            {
                e.Page.MdiChild.Dispose();
            }
            if (xtraTabbedMdiMgr.Pages.Count == 0)
            {
                xtraTabbedMdiMgr.MdiParent = null;
                this.IsMdiContainer = false;
            }
        }

        private void bsiVersion_ItemClick(object sender, ItemClickEventArgs e)
        {
            Globals.ShowInfoNotice(this, "我也就是测试一下");
            Globals.ShowWarningNotice(this, "我也就是测试二下");
            Globals.ShowErrorNotice(this, "我也就是测试三下");
        }

        private void FrmMain_Resize(object sender, EventArgs e)
        {
            BackgroundImage = Image.FromFile(Globals.appConfigure.AppPath + "\\BackPct.jpg");
            BackgroundImageLayout = ImageLayout.Stretch;
        }

        public void OpenForm(string menuName, string dllName, string formName, object[] param = null)
        {
            SysMenu menu = new SysMenu();
            menu.PATH = dllName;
            menu.COMPONENT = formName;
            menu.MENU_NAME = menuName;
            menu.PARMS = param;
            CreateMdiControl(menu);
        }

        public void OpenAlwaysNewForm(string menuName, string dllName, string formName, object[] param = null)
        {
            SysMenu menu = new SysMenu();
            menu.PATH = dllName;
            menu.COMPONENT = formName;
            menu.MENU_NAME = menuName;
            menu.PARMS = param;
            CreateMdiControl(menu);
        }

        private void bbiRefreshCache_ItemClick(object sender, ItemClickEventArgs e)
        {
            ShowLoading("正在刷新系统缓存,请稍后...");
            try
            {
                SysCache.InitCache();
            }
            finally
            {
                CloseLoading();
            }
        }

        private void ShowXtraTabbedMdiMgr()
        {
            this.xtraTabbedMdiMgr = new DevExpress.XtraTabbedMdi.XtraTabbedMdiManager(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.xtraTabbedMdiMgr)).BeginInit();
            this.xtraTabbedMdiMgr.ClosePageButtonShowMode = DevExpress.XtraTab.ClosePageButtonShowMode.InActiveTabPageAndTabControlHeader;
            this.xtraTabbedMdiMgr.MdiParent = this;
            this.xtraTabbedMdiMgr.PageImagePosition = DevExpress.XtraTab.TabPageImagePosition.None;
            this.xtraTabbedMdiMgr.PageRemoved += new DevExpress.XtraTabbedMdi.MdiTabPageEventHandler(this.xtraTabbedMdiMgr_PageRemoved);
            ((System.ComponentModel.ISupportInitialize)(this.xtraTabbedMdiMgr)).EndInit();
        }

        private void bbiSwitch_ItemClick(object sender, ItemClickEventArgs e)
        {
            FrmChangeSys frmChangeSys = new FrmChangeSys();
            if (frmChangeSys.ShowDialog() == DialogResult.OK)
            {
                var changeSys = frmChangeSys.changeSys;
                _isQuit = true;
                StartUpArgs startUpArgs = new StartUpArgs();
                startUpArgs.SYSID = changeSys.SYS_ID.ToString();
                startUpArgs.LOGINNAME = Globals.CurrentUser.LoginName;
                startUpArgs.PASSWORD = Globals.CurrentUser.Password;
                Process.Start(Application.ExecutablePath, startUpArgs.GetStartUpArgsString());
                Application.Exit();
            }
        }

        void IMdiForm.ShowDialog()
        {
            this.ShowDialog();
        }
    }
}